package p.ithorns.framework.crypto.advice;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import p.ithorns.framework.crypto.core.Crypto;
import p.ithorns.framework.crypto.core.CryptoProperties;
import p.ithorns.framework.crypto.core.NeedCrypto;

/**
 * EncryptResponseBodyAdvice
 *
 * @author ithorns
 * @version 1.0
 * @date 2019/5/24 13:44
 */
@ControllerAdvice
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice {

    private final static Logger log = LoggerFactory.getLogger(EncryptResponseBodyAdvice.class);


    private static final ThreadLocal<Boolean> encryptLocal = new ThreadLocal<>();

    @Autowired
    private Crypto crypto;

    @Autowired
    private CryptoProperties properties;

    private final ObjectMapper objectMapper = new ObjectMapper();

    public static void setEncryptStatus(boolean status) {
        encryptLocal.set(status);
    }


    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        Boolean status = encryptLocal.get();
        if (status != null && !status) {
            encryptLocal.remove();
            return body;
        }

        if (NeedCrypto.needEncrypt(methodParameter)) {
            try {
                objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);
                //获取到返回数据
                String content = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);
                if (!StringUtils.hasText(properties.getPrivateKey())) {
                    throw new NullPointerException("需要配置crypto.privatekey参数");
                }

                //进行加密操作
                return crypto.encrypt(content, properties.getPublicKey());
            } catch (Exception e) {
                log.error("加密数据异常", e);
            }
        }
        return body;
    }
}
